<?php

namespace Home\Controller;

use Think\Controller;
use Org\Util\Rbac;

class IndexController extends Controller
{
    public function index()
    {
        $this->redirect('logOn');
    }

    // 用户登录
    public function logOn()
    {
        $this->display();
    }

    // 用户登录操作，操作需要记录
    public function logOnHandler()
    {
        if (IS_POST) {
            session(null);
            $map['user_name'] = I('post.user_name', null);
            $map['password'] = md5(I('post.password', null));
            $user = M('user');
            $result = $user->where($map)->find();
            if ($result) {
                $user->where(array('id' => $result['id']))->save(array('logtime' => time(), 'logip' => get_client_ip()));
                session(C('USER_AUTH_KEY'), $result['id']);//保存登录用户的id
                session('user_name', $result['user_name']);//保存登录通话的账号
                session('logtime', time());                //保存登录时间
                session('logip', get_client_ip());         //保存登录ip
                Rbac::saveAccessList();
                if ($result['user_name'] == C('RBAC_SUPERADMIN')) {
                    session(C('ADMIN_AUTH_KEY'), true);//超级管理员标示
                }
                $this->redirect('lock');
            } else {
                $this->error('密码或者用户名错误', U('Home/Index/logOn'), 3);
            }
        }
    }

    // 判断用户是否锁定
    public function lock()
    {
        $user = M('user');
        $result = $user->where(array('id' => session(C('USER_AUTH_KEY'))))->find();
        $part = M('userinfo')->getFieldByUid($result['id'], 'part');
        $role = M('role');
        $role_user = M('role_user');
        $roleIDs = $role_user->where(['user_id' => $result['id']])->find();
        $roles = $role->where(['id' => $roleIDs['role_id']])->find();
        if ($result['lock'] == 0 && $part == 'system') {
            if ($roles['name'] != '领导视图'){
                //如果不是领导视图只是系统用户
                session('form', 'usermanage');//系统用户标示
                $this->redirect('Home/User/index');
            } elseif ($roles['name'] == '领导视图') {
                session('form', 'usermanage');//系统用户标示
                $this->redirect('Home/Phone/index');
            }

        } elseif (session(C('ADMIN_AUTH_KEY'))) {
            session('form', 'usermanage');
            $this->redirect('Home/User/index');
        } elseif ($result['lock'] == 0 && $part == 'unit') {
            //只是单位用户
            $this->redirect('Home/Module/index');
        } elseif ($result['lock'] == 1) {
            $this->error('已结被冻结', U('Home/Index/logOn'), 3);
        }
    }

    // 退出登录
    public function logout()
    {
        session(null);//登出清空session
        $this->redirect('logOn');
    }
}
